<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
/**
 * 服务管理
 * @package app\erp\admin
 */
class Service extends Admin
{
	/**
     * 服务列表
     * @author Naruto
     * @return mixed
     */
    public function index(){
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
		// 获取筛选
		$map = $this->getMap();

		//数据获取
        $data = input();
		$class_id 		= isset($data['class_id']) ? $data['class_id'] : 0;
        if($class_id > 0){
            $map_r = [];
            $map_r[] = ['path', ['like', $class_id.'-%'], ['like', '%-'.$class_id.'-%'], 'or'];
            $class_path = model('ErpServiceClass') -> where($map_r) -> column('id');
            $map[] = ['service_classid', 'in', $class_path];
        }
		
		// 数据列表
		$data_list = model('ErpService', 'model') -> where($map) -> order('create_time desc') -> paginate();
		foreach($data_list as $key => $value){
            $service_class = model('ErpServiceClass') -> find($value['service_classid']) -> title;
            $data_list[$key]['service_class'] = $service_class;

            $data_list[$key]['store_title'] = $value['store_id'] == 0 ? '全店通用' : $store_title = model('ErpStore') -> find($value['store_id']) -> title;
        }

        $edit_service = [
			'title' => '编辑',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('edit_service', ['service_id' => '__id__']),
		];
			
		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('服务列表') // 设置页面标题
            ->setTableName('erp_service') // 设置数据表名
            ->addColumns([ // 批量添加列
				['id', 'id'],
                ['service_name', '服务名称', 'text.edit'],
                ['mobile', '手机号', 'text.edit'],
				['price', '服务价格', 'text.edit'],
				//['description', '服务说明'],
				['service_class', '服务分类'],
				['store_title', '所属门店'],
                ['right_button', '操作', 'btn']
            ])
            ->setSearchArea([
                ['text', 'service_name', '服务名称', 'like'],
                ['select', 'service_classid', '服务分类', '', '', model('ErpServiceClass') -> getMenuTree(0, '')],
            ])
			->addRightButton('edit_service', $edit_service ,true) // 批量添加右侧按钮
			->addRightButton('delete') // 批量添加右侧按钮
			->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染页面
	}
	
	/**
     * 编辑
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit_service($service_id = ''){
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');
            $data['id'] = $service_id;
            //数据验证
            $Validate = validate('Service', 'validate');
            if( !$Validate -> scene('service_edit') -> check($data) ){
                $this->error($Validate -> getError());
            }

			//图片上传
			if($data['pic1']){
				$pic_arr = explode(',', $data['pic1']);
				$cover_video_arr = [];
				foreach ($pic_arr as $key => $value) {
					if(is_numeric($value)){
						//获取本地路径
						$avatar_url = model('admin/Attachment') -> getFilePath($value, 1);
						//获取本地附件信息
						$attachment_info = model('admin/Attachment') -> find($value);
						//上传OSS
						$rel = controller('common/Osslogic', 'logic') -> uploadFile($avatar_url, 'service/'.$avatar_url);
						$avatar_url_rel = $rel['data']['info']['url'];

						$data_list = [
							'uid' => 1,
							'img_url' => $avatar_url_rel,
							'width'	=> $attachment_info['width'],
							'height'	=> $attachment_info['height'],
							'create_time' => time(),
							'update_time' => time(),
						];
						$cover_video_arr[] = model('ErpServiceImgs') -> insertGetId($data_list);
					}else{
						foreach(json_decode($data['coverimgArr'], true) as $k => $v){
							if($value == $v['img_url']){
								$cover_video_arr[] = $v['id'];
							}
						}
					}
				}
			}
			if($data['pic2']){
				$pic_arr = explode(',', $data['pic2']);
				$details_arr = [];
				foreach ($pic_arr as $key => $value) {
					if(is_numeric($value)){
						//获取本地路径
						$avatar_url = model('admin/Attachment') -> getFilePath($value, 1);
						//获取本地附件信息
						$attachment_info = model('admin/Attachment') -> find($value);
						//上传OSS
						$rel = controller('common/Osslogic', 'logic') -> uploadFile($avatar_url, 'goods_suoluetu/'.$avatar_url);
						$avatar_url_rel = $rel['data']['info']['url'];

						$data_list = [
							'img_url' => $avatar_url_rel,
							'width'	=> $attachment_info['width'],
							'height'	=> $attachment_info['height'],
							'create_time' => time(),
							'update_time' => time(),
						];
						$details_arr[] = model('ErpServiceImgs') -> insertGetId($data_list);

					}else{
						foreach(json_decode($data['detailsimgArr'], true) as $k => $v){
							if($value == $v['img_url']){
								$details_arr[] = $v['id'];
							}
						}
					}
				}
			}

            //添加产品缩略图表
            //删除
            $map = [];
            $map['service_id'] = $service_id;
            $rel = model('ErpServiceCoverimg') -> where($map) -> delete();
            $cover_arr = [];
            foreach ($cover_video_arr as $key => $value) {
                $cover_arr[] = [
                    'service_id'     => $service_id,
                    'img_id'         => $value,
                ];
            }
            $rel = model('ErpServiceCoverimg') -> saveAll($cover_arr);//dump($rel);
            if(!$rel){
                $this -> error('编辑失败');
            }
            //添加产品详情图表
            //删除
            $map = [];
            $map['service_id'] = $service_id;
            $rel = model('ErpServiceDetails') -> where($map) -> delete();
            $cover_arr = [];
            foreach ($details_arr as $key => $value) {
                $cover_arr[] = [
                    'service_id'     => $service_id,
                    'img_id'         => $value,
                ];
            }
            $rel = model('ErpServiceDetails') -> saveAll($cover_arr);//dump($rel);
            if(!$rel){
                $this -> error('编辑失败');
            }

			//数据规整
			$service_name       = $data['service_name'];
            $price              = $data['price'];
            $service_classid    = $data['service_classid'];
            $description        = $data['description'];
            $store_id           = $data['store_id'];
            $mobile           = $data['mobile'];

			//数据插入
			$rel = model('ErpService')-> editData($service_id, $service_name, $price, $service_classid, $description, $store_id, $mobile);
			
			if($rel['code'] == 200){
				$this -> success('编辑成功', '', '_parent_reload');
			}
		}

		$service_info = model('ErpService') -> find($service_id);

		//缩略图
		$coverlistimgArr = [];
		$coverlistimgArr_id = [];
		$cover_id = model('ErpServiceCoverimg') -> where('service_id', $service_id) -> column('img_id');//dump($params);
		$coverlist = model('ErpServiceImgs') -> where([['id', 'in', $cover_id]]) -> column('id,img_url');//dump($params);
		if(!empty($coverlist)){
			foreach($coverlist as $key => $value){
				if($value != ''){
					$coverlistimgArr_id[] = [
					    'id' => $key,
                        'img_url' => $value
                    ];
					$coverlistimgArr[] 	  = $value;
				}
			}
		}
		//详情图
		$detailsImgArr_id = [];
		$detailsImgArr = [];
        $details_id = model('ErpServiceDetails') -> where('service_id', $service_id) -> column('img_id');//dump($params);
        $detailslist = model('ErpServiceImgs') -> where([['id', 'in', $details_id]]) -> column('id,img_url');//dump($params);
		if(!empty($detailslist)){
			foreach($detailslist as $key => $value){
				if($value != ''){
                    $detailsImgArr_id[] = [
                        'id' => $key,
                        'img_url' => $value
                    ];
					$detailsImgArr[] 	= $value;
				}
			}
		}

        $service_info['pic1'] 	 	 	 = implode(',', $coverlistimgArr);
        $service_info['pic2'] 	 	 	 = implode(',', $detailsImgArr);
        $service_info['coverimgArr']	 = json_encode($coverlistimgArr_id);
        $service_info['detailsimgArr']   = json_encode($detailsImgArr_id);

        $store_list = model('ErpStore') -> column('id,title');
        $store_list[0] = '全店通用';
		//根据类目添加参数
		return ZBuilder::make('form')
			->setPageTitle('编辑服务')
			->addText('service_name', '服务名称[:请输入名称]')
			->addText('mobile', '服务电话[:请输入电话]')
			->addText('price', '服务价格[:请输入价格]')
			->addTextarea('description', '服务介绍[:请输入服务介绍]')
            ->addSelect('store_id', '门店','请选择门店', $store_list)
			->addLinkages('service_classid', '选择服务分类', '', 'erp_service_class', 2, '', ['name' => 'title'])
			->addImages_oss('pic1', '缩略图')
			->addImages_oss('pic2', '详情图')
			->setFormData($service_info)
            ->addFormItems([ // 批量添加表单项
                ['hidden', 'coverimgArr'],
                ['hidden', 'detailsimgArr'],
            ])
			//->isAjax(false)
            ->fetch();
	}

    /**
     * 添加
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add_service(){
        // 保存数据
        if ($this->request->isPost()) {
            //数据接收
            $data = $this->request->post('', null, 'trim');

            //数据验证
            $Validate = validate('Service', 'validate');
            if( !$Validate -> scene('service_add') -> check($data) ){
                $this->error($Validate -> getError());
            }
			
			$cover_video_arr = [];
            //图片上传
            if($data['pic1']){
                $pic_arr = explode(',', $data['pic1']);
                foreach ($pic_arr as $key => $value) {
                    if(is_numeric($value)){
                        //获取本地路径
                        $avatar_url = model('admin/Attachment') -> getFilePath($value, 1);
                        //获取本地附件信息
                        $attachment_info = model('admin/Attachment') -> find($value);
                        //上传OSS
                        $rel = controller('common/Osslogic', 'logic') -> uploadFile($avatar_url, 'service/'.$avatar_url);
                        $avatar_url_rel = $rel['data']['info']['url'];

                        $data_list = [
                            'uid' => 1,
                            'img_url' => $avatar_url_rel,
                            'width'	=> $attachment_info['width'],
                            'height'	=> $attachment_info['height'],
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                        $cover_video_arr[] = model('ErpServiceImgs') -> insertGetId($data_list);
                    }else{
                        foreach(json_decode($data['coverimgArr'], true) as $k => $v){
                            if($value == $v['img_url']){
                                $cover_video_arr[] = $v['id'];
                            }
                        }
                    }
                }
            }
			$details_arr = [];
            if($data['pic2']){
                $pic_arr = explode(',', $data['pic2']);
                foreach ($pic_arr as $key => $value) {
                    if(is_numeric($value)){
                        //获取本地路径
                        $avatar_url = model('admin/Attachment') -> getFilePath($value, 1);
                        //获取本地附件信息
                        $attachment_info = model('admin/Attachment') -> find($value);
                        //上传OSS
                        $rel = controller('common/Osslogic', 'logic') -> uploadFile($avatar_url, 'goods_suoluetu/'.$avatar_url);
                        $avatar_url_rel = $rel['data']['info']['url'];

                        $data_list = [
                            'img_url' => $avatar_url_rel,
                            'width'	=> $attachment_info['width'],
                            'height'	=> $attachment_info['height'],
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                        $details_arr[] = model('ErpServiceImgs') -> insertGetId($data_list);
                    }else{
                        foreach(json_decode($data['detailsimgArr'], true) as $k => $v){
                            if($value == $v['img_url']){
                                $details_arr[] = $v['id'];
                            }
                        }
                    }
                }
            }
            //数据规整
            $service_name       = $data['service_name'];
            $price              = $data['price'];
            $service_classid    = $data['service_classid'];
            $description        = $data['description'];
            $store_id           = $data['store_id'];
            $mobile           = $data['mobile'];
			
			if(empty($cover_video_arr)){
				 $this -> error('请上传缩略图');
			}
			
            //数据插入
            $rel = model('ErpService')-> addData($service_name, $price, $service_classid, $description, $store_id, $mobile);

            if($rel['code'] == 200){
                $service_id = $rel['data'];
                //添加产品缩略图表
                $cover_arr = [];
                foreach ($cover_video_arr as $key => $value) {
                    $cover_arr[] = [
                        'service_id'     => $service_id,
                        'img_id'         => $value,
                    ];
                }
                $rel = model('ErpServiceCoverimg') -> saveAll($cover_arr);//dump($rel);
                if(!$rel){
                    $this -> error('添加失败');
                }

                //添加产品详情图表
                $cover_arr = [];
                foreach ($details_arr as $key => $value) {
                    $cover_arr[] = [
                        'service_id'     => $service_id,
                        'img_id'         => $value,
                    ];
                }
                $rel = model('ErpServiceDetails') -> saveAll($cover_arr);//dump($rel);
                if(!$rel){
                    $this -> error('添加失败');
                }

                $this -> success('添加成功', url('index'));
            }
        }
        $store_list = model('ErpStore') -> column('id,title');
        $store_list[0] = '全店通用';
        //根据类目添加参数
        return ZBuilder::make('form')
            ->setPageTitle('添加服务')
            ->addText('service_name', '服务名称[:请输入名称]')
			->addText('mobile', '服务电话[:请输入电话]')
            ->addText('price', '服务价格[:请输入价格]')
            ->addTextarea('description', '服务介绍[:请输入服务介绍]')
            ->addSelect('store_id', '门店','请选择门店', $store_list, 0)
            ->addLinkages('service_classid', '选择服务分类', '', 'erp_service_class', 2, '', ['name' => 'title'])
            ->addImages_oss('pic1', '缩略图', '', '', '', '', '', ['size' => '500,500'])
            ->addImages_oss('pic2', '详情图', '', '', '', '', '', ['size' => '500,500'])
            ->fetch();
    }
}

